import router from './router'
import store from './store'
import { getToken } from '@/utils/auth'

// 配置白名单
const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  // document.title = to.meta.title
  // 报错页面
  if (to.path === '/OtherError' || to.path === '/transitPage') {
    next()
    return
  }
  const isToken = getToken()
  if (isToken) {
    if (to.path === '/login') {
      // 如果已经登录了重定向去主页
      next({ path: '/' })
    } else {
      // 兼容后台没有配置权限列表的清空
      const authRoutes =
        store.getters.authRoutes && store.getters.authRoutes.length
      if (authRoutes) {
        const hideRouter = function (showName) {
          let tmps = store.getters.permission_routes.map((item) => {
            item.hidden = true
            if (item.name === showName) item.hidden = false
            return item
          })
          store.dispatch('permission/hideRoutes', tmps)
        }
        if (to.meta.className) {
          hideRouter(to.meta.className)
        }
        next()
      } else {
        try {
          // 请求权限界面
          const authPageRoutes = await store.dispatch('user/getInfo')
          // 通过后台的权限筛选路由
          const accessRoutes = await store.dispatch(
            'permission/generateRoutes',
            authPageRoutes
          )
          accessRoutes.forEach((item) => {
            router.addRoute(item)
          })
          next({ ...to, replace: true })
        } catch (error) {
          // 删除token
          await store.dispatch('user/resetToken')
          next()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})
